﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.IO;

namespace WP7_calendar.Model.WebStorage
{
    public class Facebook
    {
        private string m_accessToken;
        public ObservableCollection<AgendaItem> Result;
        public bool IsBusy;

        public Facebook()
        {
            Result = new ObservableCollection<AgendaItem>();
        }

        /// <summary>
        /// Begins async webdownload. Access token is a security feature of Facebook.
        /// To test, usually have to replace with another one specific for ones own account
        /// Access tokens can be generated at: http://developers.facebook.com/tools/explorer
        /// </summary>
        public void Update()
        {
            IsBusy = true;
            WebClient client = new WebClient();
            m_accessToken = "AAACEdEose0cBACJiFPXgW6aSxeTUK7PdlWZCny1UzZAGP5QepzIjVsnfrj6EDKCqfxZA2lyy1KwSKgxqdUopvzEa2svQ3wgMW1pnwCziwZDZD"; // Only for development purposes, must be refreshed about every hour
            client.DownloadStringAsync(new Uri("https://graph.facebook.com/me/events?access_token=" + m_accessToken));
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        }

        /// <summary>
        /// Event handler that is run when the async download is finished
        /// </summary>
        /// <param name="e">Contains the downloaded data, or an error when appropriate</param>
        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            IsBusy = false;
            if (e.Error != null)
            {
                Debug.WriteLine(e.Error.Message);
            }
            else if (e.Result.Contains("data"))
            {
                string data = e.Result.Substring(e.Result.IndexOf("\"name\""));

                while(data.Contains("name")) // Parse each event data
                {
                    string header = data.Substring(8, data.IndexOf("\",\"") - 8);
                    
                    data = data.Substring(data.IndexOf("\",\"")+3);
                    
                    string date = data.Substring(13, data.IndexOf("\",\"") - 13);
                    string[] dateComponents = date.Substring(0,date.IndexOf('T')).Split('-');
                    date = String.Format("{0},{1},{2}",dateComponents[1],dateComponents[2],dateComponents[0]);

                    string time = date.Substring(date.IndexOf("T")+1);

                    data = data.Substring(data.IndexOf("\",\"location") + 3);
                    
                    string location = data.Substring(11, data.IndexOf("\",\"") - 11);

                    data = data.Substring(data.IndexOf("},{") + 3);

                    Result.Add(new AgendaItem(header, date, time, location));
                }
            }
        }
    }
}
